package com.neighbor.neighborhooduser.service.impl;

import com.neighbor.neighborhooduser.pojo.PostCollections;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.neighbor.neighborhooduser.dao.IPostLikesDao;
import com.neighbor.neighborhooduser.dao.IPostsDao;
import com.neighbor.neighborhooduser.pojo.*;
import com.neighbor.neighborhooduser.dao.IPostCollectionsDao;
import com.neighbor.neighborhooduser.service.IPostCollectionsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.neighbor.neighborhooduser.utils.ReOpe;
import com.neighbor.neighborhooduser.utils.ResponseMsg;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 帖子收藏记录表 服务实现类
 * </p>
 *
 * @author song
 * @since 2025-09-22 09:13:04
 */
@Service
public class PostCollectionsServiceImpl extends ServiceImpl<IPostCollectionsDao, PostCollections> implements IPostCollectionsService {

    @Autowired
    private ReOpe reOpe;
    @Autowired
    private IPostCollectionsDao postCollectionsDao;
    @Autowired
    private IPostsDao postsDao;


    @Override
    public Boolean setCollect(Integer postId, HttpServletRequest request) {
        ResponseMsg responseMsg = reOpe.IsToken(request);
        if (responseMsg.getCode() != ResponseMsg.SUCCESS) {

            return false;
        }
        Users user = (Users) responseMsg.getData();
        QueryWrapper<PostCollections> wrapper = new QueryWrapper<>();
        wrapper.eq("post_id",postId)
                .eq("user_id",user.getUserId());
        boolean isCollected = postCollectionsDao.exists(wrapper);
        if(isCollected){
            postCollectionsDao.delete(wrapper);
            Posts post = postsDao.selectById(postId);
            post.setIsCollected(false);
            UpdateWrapper<Posts> PostsWrapper = new UpdateWrapper<>();
            PostsWrapper.set("collect_count",post.getCollectCount()-1)
                    .eq("post_id",postId);
            postsDao.update(PostsWrapper);
            return false;
        }else{
            PostCollections postCollections = new PostCollections();
            postCollections.setPostId(postId);
            postCollections.setUserId(user.getUserId());
            postCollectionsDao.insert(postCollections);
            Posts post = postsDao.selectById(postId);
            post.setIsCollected(true);
            UpdateWrapper<Posts> PostsWrapper = new UpdateWrapper<>();
            PostsWrapper.set("collect_count",post.getCollectCount()+1)
                    .eq("post_id",postId);
            postsDao.update(PostsWrapper);
            return true;
        }
    }
}
